package com.android.systemui.ios.views;

import android.app.UiModeManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.systemui.ios.IActionEventCallback;
import com.android.systemui.ios.IGuardService;
import com.android.systemui.ios.IStatusBarCallback;
import com.android.systemui.ios.R;

public class PageShortcutView extends FrameLayout {

    private boolean mAutomatic;

    private View mZoomInView;
    private View mZoomOutView;
    private View mOverlayView;

    private ShortcutIconView mShortcutMain;
    private ShortcutSlideView mZoomInBrightness;
    private ShortcutSlideView mZoomOutBrightness;

    private IGuardService mService;
    private IActionEventCallback mCallback;

    private View mBrightnessDarkMode;
    private ImageView mDarkModeIcon;
    private TextView mDarkModeText;

    private View mBrightnessNightShift;
    private ImageView mNightShiftIcon;
    private TextView mNightShiftText;

    private View mBrightnessTrueTone;
    private ImageView mTrueToneIcon;
    private TextView mTrueToneText;

    private final UiModeManager mUiModeManager;
    private final SharedPreferences mPreferences;
    private final String LINE_ON;
    private final String LINE_OFF;

    public PageShortcutView(Context context) {
        this(context, null, 0);
    }

    public PageShortcutView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PageShortcutView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        int automatic = Settings.System.getInt(context.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        mAutomatic = automatic != Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;

        mUiModeManager = (UiModeManager) context.getSystemService(Context.UI_MODE_SERVICE);
        mPreferences = PreferenceManager.getDefaultSharedPreferences(context);

        LINE_ON = "\n" + getResources().getString(R.string.ip_shortcut_switch_on);
        LINE_OFF = "\n" + getResources().getString(R.string.ip_shortcut_switch_off);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mShortcutMain = findViewById(R.id.ip_shortcut_main_layout);
        mOverlayView = findViewById(R.id.ip_overlay_black_color);
        mZoomOutView = findViewById(R.id.ip_shortcut_zoom_out_layout);
        mZoomInView = findViewById(R.id.ip_shortcut_zoom_in_layout);
        mZoomInView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mZoomInView.animate().alpha(0.0f).withEndAction(() -> mZoomInView.setVisibility(GONE)).start();
                mZoomOutView.animate().alpha(1.0f).withStartAction(() -> {
                    mZoomOutView.setAlpha(0.0f);
                    mZoomOutView.setVisibility(VISIBLE);
                }).start();
                mZoomOutBrightness.setProgress(getCurrentBrightness());
            }
        });

        mZoomOutBrightness = (ShortcutSlideView) mZoomOutView.findViewById(R.id.ip_shortcut_slide_control_brightness);
        mZoomOutBrightness.setPagerView(this);
        mZoomOutBrightness.setLongClickEnable(true);

        mZoomInBrightness = (ShortcutSlideView) mZoomInView.findViewById(R.id.ip_shortcut_slide_control_brightness);
        mZoomInBrightness.setClickAnimationEnable(false);
        if (mService != null) {
            mZoomInBrightness.setMaxMin(mService.getBrightnessMax(), mService.getBrightnessMin(), true);
            mZoomInBrightness.setProgress(getCurrentBrightness());
        }
        mZoomInBrightness.setOnShortcutSlideChangedListener(new ShortcutSlideView.OnShortcutSlideChangedListener() {

            @Override
            public void onChanged(int max, int min, int progress, boolean tracking) {
                updateBrightness(max, min, progress, tracking);
            }
        });

        mBrightnessDarkMode = mZoomInView.findViewById(R.id.ip_brightness_ctrl_dark_mode);
        mBrightnessDarkMode.setOnClickListener(mDarkModeClick);
        mDarkModeIcon = (ImageView) mBrightnessDarkMode.findViewById(android.R.id.icon1);
        mDarkModeText = (TextView) mBrightnessDarkMode.findViewById(android.R.id.text1);
        updateDarkMode();

        mBrightnessNightShift = mZoomInView.findViewById(R.id.ip_brightness_ctrl_night_shift);
        mBrightnessNightShift.setOnClickListener(mNightShiftClick);
        mNightShiftIcon = (ImageView) mBrightnessNightShift.findViewById(android.R.id.icon1);
        mNightShiftText = (TextView) mBrightnessNightShift.findViewById(android.R.id.text1);
        if (mPreferences.getBoolean("key_night_shift", false)) {
            mNightShiftIcon.setSelected(true);
            mNightShiftText.setText(getResources().getString(R.string.ip_shortcut_brightness_night_shift) + LINE_ON);
        } else {
            mNightShiftIcon.setSelected(false);
            mNightShiftText.setText(getResources().getString(R.string.ip_shortcut_brightness_night_shift) + LINE_OFF);
        }

        mBrightnessTrueTone = mZoomInView.findViewById(R.id.ip_brightness_ctrl_true_tone);
        mBrightnessTrueTone.setOnClickListener(mTrueToneClick);
        mTrueToneIcon = (ImageView) mBrightnessTrueTone.findViewById(android.R.id.icon1);
        mTrueToneText = (TextView) mBrightnessTrueTone.findViewById(android.R.id.text1);
        if (mPreferences.getBoolean("key_true_tone", false)) {
            mTrueToneIcon.setSelected(true);
            mTrueToneText.setText(getResources().getString(R.string.ip_shortcut_brightness_true_tone) + LINE_ON);
        } else {
            mTrueToneIcon.setSelected(false);
            mTrueToneText.setText(getResources().getString(R.string.ip_shortcut_brightness_true_tone) + LINE_OFF);
        }

        setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mCallback != null) {
                    mCallback.onShortcutClose();
                }
            }
        });
    }

    public IStatusBarCallback getShortcutIcons() {
        return mShortcutMain;
    }

    public void setActionEventCallback(IGuardService service, IActionEventCallback callback) {
        mService = service;
        mCallback = callback;
        mShortcutMain.setActionEventCallback(service, callback);
        if (mZoomInBrightness != null && mService != null) {
            mZoomInBrightness.setMaxMin(mService.getBrightnessMax(), mService.getBrightnessMin(), true);
            mZoomInBrightness.setProgress(getCurrentBrightness());
        }
    }

    public void postRefresh() {
        if (mService != null) {
            mService.postRefresh();
        }
        mShortcutMain.onPanelExpandChanged(true);
    }

    private void updateDarkMode() {
        if (mUiModeManager.getNightMode() == UiModeManager.MODE_NIGHT_YES) {
            mDarkModeIcon.setSelected(true);
            mDarkModeText.setText(getResources().getString(R.string.ip_shortcut_brightness_dark_mode) + LINE_ON);
            mOverlayView.setAlpha(0.5f);
        } else {
            mDarkModeIcon.setSelected(false);
            mDarkModeText.setText(getResources().getString(R.string.ip_shortcut_brightness_dark_mode) + LINE_OFF);
            mOverlayView.setAlpha(0.0f);
        }
    }

    public void closeZoomIn() {
        if (mZoomInView.isShown()) {
            mZoomInView.setVisibility(GONE);
            mZoomOutView.setAlpha(1.0f);
            mZoomOutView.setVisibility(VISIBLE);
        }
    }

    public void openZoomIn() {
        updateDarkMode();
        mZoomOutView.animate().alpha(0.0f).withEndAction(() -> mZoomOutView.setVisibility(GONE)).start();
        mZoomInView.animate().alpha(1.0f).withStartAction(() -> {
            mZoomInView.setAlpha(0.0f);
            mZoomInView.setVisibility(VISIBLE);
        }).start();
        mZoomInBrightness.setProgress(getCurrentBrightness());
    }

    private void updateBrightness(int max, int min, int progress, boolean tracking) {
        if (!mAutomatic) {
            if (mService != null) {
                mService.setBrightnessValue(progress);
            }
        } else {
            final float adj = progress / (2048 / 2f) - 1; //BRIGHTNESS_ADJ_RESOLUTION = 2048
            if (mService != null) {
                mService.setBrightnessAdj(adj);
            }
        }
    }

    private int getCurrentBrightness() {
        float value = 108;
        if (mService != null) {
            if (mAutomatic) {
                value = mService.getBrightnessAdj();
            } else {
                value = mService.getBrightnessCurrent();
            }
        }
        return (int) value;
    }

    private void updateBrightnessState() {
        int automatic = mService.getBrightnessAutomatic();
        mAutomatic = automatic != Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;
        mZoomInBrightness.setProgress(getCurrentBrightness());
    }

    private final Runnable mDarkModeEnableRunnable = new Runnable() {

        @Override
        public void run() {
            mBrightnessDarkMode.setEnabled(true);
        }
    };

    private final Runnable mDarkModeNightYes = new Runnable() {

        @Override
        public void run() {
            mDarkModeIcon.setSelected(true);
            mUiModeManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
            getContext().sendBroadcast(new Intent("android.ext.UI_MODE_CHANGED"));
        }
    };

    private final Runnable mDarkModeNightNo = new Runnable() {

        @Override
        public void run() {
            mDarkModeIcon.setSelected(false);
            mUiModeManager.setNightMode(UiModeManager.MODE_NIGHT_NO);
            getContext().sendBroadcast(new Intent("android.ext.UI_MODE_CHANGED"));
        }
    };

    private final OnClickListener mDarkModeClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            removeCallbacks(mDarkModeNightYes);
            removeCallbacks(mDarkModeNightNo);
            mOverlayView.animate().cancel();
            if (mDarkModeIcon.isSelected()) {
                mDarkModeText.setText(getResources().getString(R.string.ip_shortcut_brightness_dark_mode) + LINE_OFF);
                mOverlayView.animate().alpha(0.0f).setDuration(300).start();
                postDelayed(mDarkModeNightNo, 500);
            } else {
                mDarkModeText.setText(getResources().getString(R.string.ip_shortcut_brightness_dark_mode) + LINE_ON);
                mOverlayView.animate().alpha(0.5f).setDuration(300).start();
                postDelayed(mDarkModeNightYes, 500);
            }
            //mBrightnessDarkMode.setEnabled(false);
            //postDelayed(mDarkModeEnableRunnable, 500);
        }
    };

    private final OnClickListener mNightShiftClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mPreferences.getBoolean("key_night_shift", false)) {
                mNightShiftIcon.setSelected(false);
                mNightShiftText.setText(getResources().getString(R.string.ip_shortcut_brightness_night_shift) + LINE_OFF);
                mPreferences.edit().putBoolean("key_night_shift", false).apply();
            } else {
                mNightShiftIcon.setSelected(true);
                mNightShiftText.setText(getResources().getString(R.string.ip_shortcut_brightness_night_shift) + LINE_ON);
                mPreferences.edit().putBoolean("key_night_shift", true).apply();
            }
        }
    };

    private final OnClickListener mTrueToneClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mPreferences.getBoolean("key_true_tone", false)) {
                mTrueToneIcon.setSelected(false);
                mTrueToneText.setText(getResources().getString(R.string.ip_shortcut_brightness_true_tone) + LINE_OFF);
                mPreferences.edit().putBoolean("key_true_tone", false).apply();
            } else {
                mTrueToneIcon.setSelected(true);
                mTrueToneText.setText(getResources().getString(R.string.ip_shortcut_brightness_true_tone) + LINE_ON);
                mPreferences.edit().putBoolean("key_true_tone", true).apply();
            }
        }
    };
}
